import requests
import execjs
import urllib.parse
import re
from loguru import logger
import random
import cv2
import time


class SlideCrack(object):
    def __init__(self, gap, bg):
        """
        init code
        :param gap: 缺口图片
        :param bg: 背景图片
        """
        self.gap = gap
        self.bg = bg
        # self.out = out

    @staticmethod
    def clear_white(img):
        # 清除图片的空白区域，这里主要清除滑块的空白
        img = cv2.imread(img)
        rows, cols, channel = img.shape
        min_x = 255
        min_y = 255
        max_x = 0
        max_y = 0
        for x in range(1, rows):
            for y in range(1, cols):
                t = set(img[x, y])
                if len(t) >= 2:
                    if x <= min_x:
                        min_x = x
                    elif x >= max_x:
                        max_x = x

                    if y <= min_y:
                        min_y = y
                    elif y >= max_y:
                        max_y = y
        img1 = img[min_x:max_x, min_y: max_y]
        return img1

    def template_match(self, tpl, target):
        th, tw = tpl.shape[:2]
        result = cv2.matchTemplate(target, tpl, cv2.TM_CCOEFF_NORMED)
        # 寻找矩阵(一维数组当作向量,用Mat定义) 中最小值和最大值的位置
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
        tl = max_loc
        br = (tl[0] + tw, tl[1] + th)
        cv2.rectangle(target, tl, br, (0, 0, 255), 2)
        return tl[0]

    @staticmethod
    def image_edge_detection(img):
        edges = cv2.Canny(img, 100, 200)
        return edges

    def discern(self):
        img1 = self.clear_white(self.gap)
        img1 = cv2.cvtColor(img1, cv2.COLOR_RGB2GRAY)
        slide = self.image_edge_detection(img1)

        back = cv2.imread(self.bg, 0)
        back = self.image_edge_detection(back)

        slide_pic = cv2.cvtColor(slide, cv2.COLOR_GRAY2RGB)
        back_pic = cv2.cvtColor(back, cv2.COLOR_GRAY2RGB)
        x = self.template_match(slide_pic, back_pic)
        # 输出横坐标, 即 滑块在图片上的位置
        # print(x)
        return x


def splide(x):
    # 初始坐标
    _x = 0
    _y = 0
    # 计数
    count = 0
    t = 0
    list_ = list()
    while _x < x:
        count += 1
        if _x < x / 2:
            Vx = random.choice(
                [3, 4, 5, 6, 7, 8, 3, 3, 4, 4, 4, 3, 5, 6, 4, 5, 0, 2, 3, 6, 6])
        elif x - _x < 40:
            Vx = random.choice([0, -1, -2, 1, 2, 3])
        else:
            Vx = random.choice([3, 4, 5, 6])
        Vy = random.choice([-2, -1, 0, 1, 2])
        _x += Vx
        if count == 1:
            t += random.randrange(50, 100)
        else:
            t += random.randrange(5, 12)
        list_.append([_x, Vy, t])

    # print(list_)
    return list_


session = requests.Session()
# 获取背景图片URL
# url1 = 'https://c.dun.163.com/api/v2/get?'

headers = {
    'Accept': '*/*',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Host': 'c.dun.163.com',
    'Pragma': 'no-cache',
    'Referer': 'https://dun.163.com/',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36',
}

headers1 = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36',
}

ac_token_url = 'https://c.dun.163.com/api/v2/getconf?referer=https%3A%2F%2Fdun.163.com%2Ftrial%2Fjigsaw&zoneId=&id=07e2387ab53a4d6f930b8d9a9be71bdf&ipv6=false&runEnv=10&type=2&loadVersion=2.2.2&callback=__JSONP_gw7st89_7'

response = session.get(url=ac_token_url,headers=headers).text
acToken = re.findall('"token":"(.*?)"},',response)[0]
logger.info(acToken)


with open('fp.js', encoding='utf-8') as f:
    js_ = execjs.compile(f.read())
fp = js_.call('getfp')

with open('cb.js', encoding='utf-8') as f:
    js_ = execjs.compile(f.read())
cb = js_.call('getcb')


url = 'https://c.dun.163.com/api/v2/get?referer=https%3A%2F%2Fdun.163.com%2Ftrial%2Fjigsaw&zoneId=CN31&id=07e2387ab53a4d6f930b8d9a9be71bdf&fp={}&https=true&type=2&version=2.15.4&dpr=1&dev=1&cb={}&ipv6=false&runEnv=10&group=&scene=&width=320&audio=false&token=&callback=__JSONP_xucqnb2_0'.format(
    urllib.parse.quote(fp), urllib.parse.quote(cb))
res = session.get(url=url, headers=headers).text
# logger.info(res)

bg_img_url = re.findall('"bg":\\["(.*?)","', res)[0]
splide_img_url = re.findall('"front":\\["(.*?)","', res)[0]
token = re.findall('"token":"(.*?)","', res)[0]

logger.info(bg_img_url)
logger.info(splide_img_url)
logger.info(token)

with open('bg_img.jpg', 'wb') as f:
    res = session.get(url=bg_img_url, headers=headers1).content
    f.write(res)

with open('splide.png', 'wb') as f:
    res = session.get(url=splide_img_url, headers=headers1).content
    f.write(res)


# 获取缺口坐标
s = SlideCrack('bg_img.jpg', 'splide.png')
coordinate = s.discern()
logger.info(coordinate)

x_list = splide(coordinate)
logger.info(x_list)

with open('cb.js', encoding='utf-8') as f:
    js_ = execjs.compile(f.read())
getdata = js_.call('getdata', x_list, token, coordinate)
cb = js_.call('getcb')
# logger.info(getdata)


url2 = 'https://c.dun.163.com/api/v2/check?'
parma_data = {
    'referer': 'https://dun.163.com/trial/jigsaw',
    'zoneId': 'CN31',
    'id': '07e2387ab53a4d6f930b8d9a9be71bdf',
    'token': token,
    # 'acToken': '9ca17ae2e6ffcda170e2e6eea7ed699ce982b4e625819a8fb2c45e869e9abbf83a95a9feb6f960afababd4b42af0feaec3b92abc98fc8bb164f68d8d98d44f878e8eb3c45b9aaea7a9ef34829bb7b1ca60f8ecee9e',
    'acToken':acToken,
    'data': getdata,
    'width': '320',
    'type': '2',
    'version': '2.15.4',
    'cb': cb,
    'extraData': '',
    'runEnv': '10',
    'callback': '__JSONP_bnyw38h_10',
}
res2 = session.get(url=url2, headers=headers, params=parma_data)
# logger.info(res2.url)
logger.info(res2.text)
# logger.info(url2)

